//
//  YbrLocalMusicDao.m
//  wifibox
//
//  Created by os X 10.9 on 14-12-18.
//  Copyright (c) 2014年 yinbaner. All rights reserved.
//  本地文件的数据库

#import "YbrLocalMusicDao.h"
#import <MediaPlayer/MediaPlayer.h>
#import "YbrDownDao.h"
//#import "FilesDownManage.h"

@implementation YbrLocalMusicDao

// 第一次初始化的时候设置本地的音乐
-(BOOL) firstSetLocalMusic {
    __block BOOL isOk = false;
    
    [[YbrSQLHelper getDataBase] inTransaction:^(FMDatabase *db, BOOL *rollback) {
        MPMediaQuery *everything = [[MPMediaQuery alloc] init];
        
        NSArray *itemsFromGenericQuery = [everything items];
        YbrMusicItem *musicItem = [[YbrMusicItem alloc] init];
        for (MPMediaItem *song in itemsFromGenericQuery) {
            musicItem.musicId = [[song valueForProperty: MPMediaItemPropertyPersistentID] intValue];
            musicItem.musicName = [song valueForProperty: MPMediaItemPropertyTitle];
            musicItem.singername = [song valueForProperty:MPMediaItemPropertyArtist];
            musicItem.albumname = [song valueForProperty: MPMediaItemPropertyAlbumTitle];
            musicItem.downloadurl = nil;
    
            NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
            NSString *songURLString = [songURL absoluteString];
            musicItem.file = songURLString;
            
            AVAsset* songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
            NSString* lyrics = [songAsset lyrics];
         
            musicItem.img = nil;
            musicItem.duration = [[song valueForProperty: MPMediaItemPropertyPlaybackDuration] doubleValue];
            musicItem.type = 4;
//            musicItem.timeStr = [YbrTimerUtil makeTimeStr:musicItem.duration];
            
            NSLog(@"文件的下载地址   %i    %@    %@    %@   " ,musicItem.duration ,musicItem.musicName ,musicItem.singername ,musicItem.file);
            
//            NSURL *fileURL = [NSURL URLWithString:fileName];
//            bgMusicPlayer = [[AVAudioPlayeralloc] initWithContentsOfURL:fileURLerror:nil];
            
            isOk = [db executeUpdate:@"insert into local_music (musicid ,name, singername ,albumname ,downloadurl ,file  ,img ,duration ,type ,timerstr) VALUES (?,?,?,?,?,?,?,?,?,?)",
                    [NSNumber numberWithInt:musicItem.musicId] ,
                    musicItem.musicName ,
                    musicItem.singername ,
                    musicItem.albumname ,
                    musicItem.downloadurl ,
                    musicItem.file ,
                    musicItem.img ,
                    [NSNumber numberWithInt:musicItem.duration] ,
                    [NSNumber numberWithInt:musicItem.type] ,
                    musicItem.timeStr];
        }
    }];
    
    return isOk;
}

// 这个是用到了系统的数据库
-(UIImage *) getMusicImg:(int) musicId {
    // 下面是查找专辑的图片的函数
    MPMediaPropertyPredicate *artistNamePredicate = [MPMediaPropertyPredicate predicateWithValue:[NSNumber numberWithInt:musicId] forProperty: MPMediaItemPropertyPersistentID];
    MPMediaQuery *myArtistQuery = [[MPMediaQuery alloc] init];
    [myArtistQuery addFilterPredicate: artistNamePredicate];
    NSArray *itemsFromArtistQuery = [myArtistQuery items];
    
    if(itemsFromArtistQuery != nil && itemsFromArtistQuery.count != 0) {
        // 返回的结果只取第一个
        MPMediaItem *song = [itemsFromArtistQuery objectAtIndex:0];
        MPMediaItemArtwork *artwork = [song valueForProperty: MPMediaItemPropertyArtwork];
        UIImage *artworkImage = [artwork imageWithSize:CGSizeMake(100, 100)];
        if (artworkImage) {
            return artworkImage;
        } else {
            return [UIImage imageNamed: @"noArtwork.png"];
        }
    }
    return [UIImage imageNamed: @"noArtwork.png"];
}


// 这个是同步本地的音乐
-(BOOL) noFirstSetLocalMusic {
    __block BOOL isOK = NO;
    
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        // 先将本地的歌曲中的Itus当中的歌曲去掉
        isOK = [db executeUpdateWithFormat:@"delete from local_music where type=4"];
    }];
    if(isOK) {
        [self firstSetLocalMusic];
    }
    return isOK;
}

// 返回的Arr里面放置的是YbrMusicItem对象
-(NSArray *) getLocalMusic {
    __block NSArray *musiclist;
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        FMResultSet *rs;
        // 1.查询数据
        rs = [db executeQueryWithFormat:@"select musicid ,name, singername ,albumname ,downloadurl ,file  ,img ,duration ,type ,timerstr from local_music order by type"];
        
        NSMutableArray *tempArr = [NSMutableArray array];
        while (rs.next) {
            YbrMusicItem *musicItem = [[YbrMusicItem alloc] init];
            musicItem.musicId = [rs intForColumn:@"musicid"];
            musicItem.musicName = [rs stringForColumn:@"name"];
            musicItem.singername = [rs stringForColumn:@"singername"];
            musicItem.albumname = [rs stringForColumn:@"albumname"];
            musicItem.downloadurl = [rs stringForColumn:@"downloadurl"];
            musicItem.file = [rs stringForColumn:@"file"];
            musicItem.img = [rs stringForColumn:@"img"];
            musicItem.duration = [rs intForColumn:@"duration"];
            musicItem.type = [rs intForColumn:@"type"];
            musicItem.timeStr = [rs stringForColumn:@"timerstr"];
            
            [tempArr addObject:musicItem];
            musiclist = [tempArr copy];
        }
        [rs close];
    }];
    return musiclist;
}

-(BOOL) setMusicByMusicHall:(YbrMusicItem *) musicItem {
    __block BOOL isOk = false;
    
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        
        FMResultSet *rs;
        // 1.查询数据
        rs = [db executeQueryWithFormat:@"select musicid  from local_music where name = %@",musicItem.musicName];
        if(rs.next) {
            [rs close];
            return;
        }
        
        [rs close];
        
        isOk = [db executeUpdate:@"insert into local_music (musicid ,name, singername ,albumname ,downloadurl ,file  ,img ,duration ,type ,timerstr) VALUES (?,?,?,?,?,?,?,?,?,?)",
                [NSNumber numberWithInt:musicItem.musicId] ,
                musicItem.musicName ,
                musicItem.singername ,
                musicItem.albumname ,
                musicItem.downloadurl ,
                musicItem.file ,
                musicItem.img ,
                [NSNumber numberWithInt:musicItem.duration] ,
                [NSNumber numberWithInt: musicItem.type] ,
                musicItem.timeStr];
    }];
    return isOk;
}

-(BOOL) deleMusicById:(int) musicid {
    __block BOOL isOk = false;
    
    YbrMusicItem *musicItem = [self getMusicById:musicid];
    
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        isOk = [db executeUpdateWithFormat:@"delete from local_music where musicid=%i",musicid];
    }];
    
    // 如果数据库删除成功则删除本地的 ,再删除已经下载的数据库
    if(isOk) {
        YbrDownDao *downDao = [[YbrDownDao alloc] init];
        [downDao removeDownOver:musicid];
//        [[FilesDownManage sharedFilesDownManage] deleteFinishsFileByMusicId:[NSString stringWithFormat:@"%i" ,musicid]];
        
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        BOOL bRet = [fileMgr fileExistsAtPath:musicItem.file];
        if(bRet) {
            [fileMgr removeItemAtPath:musicItem.file error:nil];
        }
    }
    
    return isOk;
}

// 只是将音乐从数据库中删除了
-(BOOL) deleMusicByIdOnlyRemoveDB:(int)musicid {
    __block BOOL isOk = false;
    
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        isOk = [db executeUpdateWithFormat:@"delete from local_music where musicid=%i",musicid];
    }];
    return isOk;
}

-(YbrMusicItem *) getMusicById:(int) musicId {
    __block YbrMusicItem *musicItem;
    [[YbrSQLHelper getDataBase] inDatabase:^(FMDatabase *db) {
        FMResultSet *rs;
        // 1.查询数据
        rs = [db executeQueryWithFormat:@"select musicid ,name, singername ,albumname ,downloadurl ,file ,img ,duration ,type ,timerstr from local_music"];
//        NSMutableArray *tempArr = [NSMutableArray array];
        while (rs.next) {
            musicItem = [[YbrMusicItem alloc] init];
            musicItem.musicId = [rs intForColumn:@"musicid"];
            musicItem.musicName = [rs stringForColumn:@"name"];
            musicItem.singername = [rs stringForColumn:@"singername"];
            musicItem.albumname = [rs stringForColumn:@"albumname"];
            musicItem.downloadurl = [rs stringForColumn:@"downloadurl"];
            musicItem.file = [rs stringForColumn:@"file"];
            musicItem.img = [rs stringForColumn:@"img"];
            musicItem.duration = [rs intForColumn:@"duration"];
            musicItem.type = [rs intForColumn:@"type"];
            musicItem.timeStr = [rs stringForColumn:@"timerstr"];
        }
        [rs close];
    }];
    return musicItem;
}


@end
